package com.baijia.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * Created by dudu on 16/7/22.
 */
public class DecriptUtil {

    public static final String PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBANEe2O4yDUN5ldy1" +
            "ZbRXSAq2nxvwMFDQ8INgBgYPMg9Qbj/31OL2YGoAzvxcSni37LU7UezewB+YNWun" +
            "A/xIBH9A6gmOtcxHm4+PgFGWRer6YMoNaKxCB6JC9HplWrr5mt0yQ8o5Fn7YD5Lo" +
            "WlnM+OlDD8cebTfruD6rK38PaEBRAgMBAAECgYAxVLmP1zbRyAjWO+R2GnDgNhxq" +
            "lsqPBfr2wtwo6cTBYBPh+zC5Ka2s0+wAFDVtLNYmGoxE+HcR/PH9JzUFeme0v56K" +
            "VTUXURvxDRKCyhxFTRlF0SK54qF0yVuYWYE7iCHAcTnDNWlQnAm8whVa0RrPJZJ5" +
            "4lJWDSo9nhHpXUKnEQJBAPzxFo3QFw6GhQAFoqiHfTclqKTJmeU0ACwFZQsXOxDe" +
            "jfTkaIZnHIonjG8L2FA9lMld7AEMVc/oRvGLom8NkxcCQQDTph9iq5xZJwWCgRxF" +
            "6zaywxBHsYBbclfLBZM/enU4/d+EeRLkOHU5qmnDhYhVwiXn0UKxnBdvulQvRDOK" +
            "fwjXAkBMjrwA2EbiQpzm0M3WrIudsWxF1C8cTIzwxgE7RiC+jl3xDWEFrRfaSPYc" +
            "dj1WrAzoleDkwFMIxokSeu0DJ9ypAkBYLIIw0jvdrHMQLoe/3UE5ciiLJbjK4DUR" +
            "IK56qKLDboi7INGtAJRdxNAxI6VrzOmLzVNSuSvOYTsHQguS7F+bAkAa7YbcZ30V" +
            "6XjRRDyjJHWxG46c3acmMaM7Z5xwr3m+Qa6y0dyM4JuKe0lPiPQfxuMOXf3VVy23" +
            "VgpyDH4SU7g3";

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String rsaSign(String content, String privateKey, String charset) throws SignatureException {
        try {
            PrivateKey priKey = getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(privateKey.getBytes()));

            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initSign(priKey);
            if (StringUtils.isEmpty(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }

            byte[] signed = signature.sign();
            return new String(Base64.encodeBase64(signed));
        } catch (Exception e) {
            throw new SignatureException("RSAcontent = " + content + "; charset = " + charset, e);
        }
    }

    public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, InputStream ins) throws Exception {
        if (ins == null || StringUtils.isEmpty(algorithm)) {
            return null;
        }

        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

        byte[] encodedKey = input2byte(ins);
        encodedKey = Base64.decodeBase64(encodedKey);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }



}
